package cc.facesign.acl.utils;

import cc.facesign.acl.bean.AclRole;
import cc.facesign.acl.service.AclMenuService;
import cc.facesign.acl.service.AclRoleService;
import cc.facesign.acl.service.TblUserService;
import cc.facesign.security.bean.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.stream.Collectors;

@Component
public class GaineUtils {

    @Autowired
    private AclMenuService menuService;

    @Autowired
    private TblUserService userService;

    @Autowired
    private AclRoleService roleService;

    /**
     * 获取LoginUser
     * @return
     */
    public LoginUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser;
    }

    /**
     * 获取当前用户id
     */
    public String getId() {
        return getLoginUser().getUser().getId();
    }

    /**
     * 获取当前用户可管理的角色菜单
     */
    public Set<String> getManageRole() {
        String id = getId();
        return null;
    }

    /**
     * 当前用户的单位里是否有该角色
     * @return true 有，false没有
     */
    public boolean haveRole(String roldId) {
        if (getId().equals("0")) return true;

        QueryWrapper<AclRole> w = new QueryWrapper<>();
        w.eq("role_id", roldId);
        Set<String> set = roleService.list(w).stream()
                .map(x -> x.getId())
                .collect(Collectors.toSet());
        return set.contains(roldId);
    }


    /**
     * 查当前用户能操作的所有角色id
     */
    public Set<String> roles() {
        String userId = getId();

        if (userId.equals("0")) {
            return roleService.list(null).stream()
                    .map(x -> x.getId())
                    .collect(Collectors.toSet());
        }

        QueryWrapper<AclRole> w = new QueryWrapper<>();
        String rid = userService.getRid(userId);
        w.eq("rid", rid);
        return roleService.list(w).stream()
                .map(x -> x.getId())
                .collect(Collectors.toSet());
    }

    /**
     * 当前是否为admin账号
     */
    public boolean isAdmin() {
        return getId().equals("0");
    }
}
